const express = require('express');
const url = require('url');
const multer = require('multer');
const path = require('path');
const moment = require('moment');
const mongoose = require('mongoose')

const  NewsController = require('../controllers/newsController.js');
const categoryModel = require('../models/category.js');
const newsModel = require('../models/news.js');

const router = express.Router();

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, '../public/uploads/'))
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname))
    }
})

const upload = multer({storage: storage})


/*1. 新闻的分类添加 */
router.get('/category/add', (req, res) => {
    res.render('category-add', {title: '新闻的分类添加', info: {}});

});

router.post('/category/store', async (req, res) => {
    // 收集数据，然后定义表的模型，入库
    let {cateName} = req.body;
    let cateObj = new categoryModel({cateName});

    let error = cateObj.validateSync();

    if (error) {
        const errorRs = [];
        for (let attr in error.errors) {
            errorRs.push(`${categoryModel.fields[attr]} 字段：${error.errors[attr]}`);
        }
        let url = '/admin/news/category/add';
        let time = 3;
        res.render('error', {errorRs, url, time});
        return;
    }

    // 信息合法
    try {
        let info = await cateObj.save();
        res.redirect('/admin/news/category/list');
    } catch (e) {
        res.redirect('/admin/news/category/add');
    }

});

/*2. 新闻的分类展示 */
router.get('/category/list', async (req, res) => {
    /*获取所有的分类信息*/
    const infos = await categoryModel.find();
    // console.log(infos);

    res.render('category-list', {title: '新闻的分类展示', infos});


});

/*3. 删除 路由参数 */
router.get('/category/delete/:id', async (req, res) => {
    /* 删除：删除的时候，我们知道删除哪一个分类信息，则我们在点击分类按钮的时候，需要传递一个分类的 _id */
    /*1. 直接通过url地址规则定义，一般我们称之为 路由参数  2. 通过 查询字符串传递*/
    // console.log(req.params);
    // res.json(req.params); // res.json() 可以把一个js对象转换为一个对象格式的字符串，方便查看，res.json会把格式化字符串的对象响应给浏览器
    let cateId = req.params.id;

    try {
        await categoryModel.deleteOne({_id: cateId});

        res.redirect('back'); // back 代表的是当前的页面的上一级页面。指的是这个的来源路径

    } catch (e) {
        res.redirect('back');

    }


});

/* 使用查询字符串传递 _id 系统的 url模块 */
router.get('/category/del', async (req, res) => {
    /* 删除：删除的时候，我们知道删除哪一个分类信息，则我们在点击分类按钮的时候，需要传递一个分类的 _id */
    /*1. 直接通过url地址规则定义，一般我们称之为 路由参数  2. 通过 查询字符串传递*/
    // console.log(url.parse(req.url, true));
    // res.json(url.parse(req.url, true));
    let cateId = url.parse(req.url, true).query.id;

    try {
        await categoryModel.deleteOne({_id: cateId});

        res.redirect('back'); // back 代表的是当前的页面的上一级页面。指的是这个的来源路径

    } catch (e) {
        res.redirect('back');

    }


});

/* 4. 编辑 */
router.get('/category/edt/:id', async (req, res) => {
    let cateId = req.params.id;
    /* 在编辑之前，应该先展示编辑内容的表单 */
    let info = await categoryModel.findOne({_id: cateId});
    res.render('category-edt', {title: '新闻的分类编辑', info});
});
router.post('/category/edtstore', async (req, res) => {

    let {cateName, _id} = req.body;

    /* 根据当前的id 去查找记录然后在更新*/
    categoryModel.findById(_id, async (error, doc) => {
        if (error) {
            res.redirect('back');
        } else {
            doc.cateName = cateName;
            await doc.save();
            res.redirect('/admin/news/category/list');

        }
    })
});

/* 5. 新闻资源列表 */
router.get('/list', NewsController.getNewsList);

/* 6. 新闻资源添加 表单展示*/
router.get('/add', async (req, res) => {
    /* 获取所有的分类信息 */
    const categoryInfo = await categoryModel.find();
    res.render('news-add', {title: '新闻的资源添加', info: {}, categoryInfo});

});
/* 新闻资源入库 */
router.post('/store', upload.single('cover'), async (req, res) => {

    let {title, markup, author, beform, viewcount, islock, descption, cateId} = req.body;

    let cover = '';

    // console.log(req.file);

    if (req.file) {
        cover = req.file.filename;
    }


    const newObj = new newsModel({title, markup, author, beform, viewcount, islock, descption, cover, cateId});

    let error = newObj.validateSync();

    if (error) {
        const errorRs = [];
        for (let attr in error.errors) {
            errorRs.push(`${newsModel.fields[attr]} 字段：${error.errors[attr]}`);
        }
        let url = '/admin/news/add';
        let time = 3;
        res.render('error', {errorRs, url, time});
        return;
    }

    try {
        let info = await newObj.save();
        res.redirect('/admin/news/list');
    } catch (e) {
        res.redirect('/admin/news/add');
    }

});

/* 7. 新闻资源的删除 */
router.get('/delete/:id', async (req, res) => {

    let newsId = req.params.id;

    try {
        await newsModel.deleteOne({_id: newsId});
        res.redirect('back');
    } catch (e) {
        res.redirect('back');

    }


});

/*8.新闻的编辑 */
router.get('/edt/:id', async (req, res) => {
    let newsId = req.params.id;
    let info = await newsModel.findOne({_id: newsId});
    const categoryInfo = await categoryModel.find();

    res.render('news-edt', {title: '新闻资源的编辑', info, categoryInfo});
});
router.post('/edtstore', upload.single('cover'), async (req, res) => {
    // console.log(req.body);

    let {_id, title, markup, author, beform, viewcount, islock, descption, cateId} = req.body;
    let cover = '';
    /* 用户有可能不修改封面图，所以在入库的时候，我们也要判断一下是否上传了图片，上传了才更新，没有上传，则我们不做处理。*/
    if (req.file) {
        cover = req.file.filename;
    }
    // console.log(_id);

    /* 根据当前的id 去查找记录然后在更新*/
    newsModel.findById(_id, async (error, doc) => {
        if (error) {
            res.redirect('back');
        } else {
            // console.log(doc);


            doc.title = title;
            doc.markup = markup;
            doc.author = author;
            doc.beform = beform;
            doc.viewcount = viewcount;
            doc.islock = islock;
            doc.descption = descption;
            doc.cateId = cateId;
            if (cover) {
                doc.cover = cover;
            }

            await doc.save();
            res.redirect('/admin/news/list');

        }
    })
});

/*9.新闻的详情 detail*/
router.get('/detail/:id', async (req, res) => {
    let newsId = req.params.id;

    // console.log('newId', newsId);

    /*尝试把 字符串_id 转换为 MongoDB 里面 ObjectId 类型 */

    const info = await newsModel.aggregate([
        {
            $match: {_id: mongoose.Types.ObjectId(newsId)} // $match 代表根据条件查询
        },
        {
            $lookup:
                {
                    /*要关联的表 category*/
                    from: "category",
                    /*自己表里面和别的表产生关系的id*/
                    localField: "cateId",
                    /*关联表的id*/
                    foreignField: "_id",
                    /*查询到的关联信息的key值*/
                    as: "cateInfo"
                }
        }]);

    // res.json( info );

    res.render('news-detail', { title: '新闻资源的详情', info: info[0], moment});


});
module.exports = router;
